/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.handler.event;

import org.apache.commons.lang.StringUtils;
import org.openmrs.module.datalogging.configuration.Event;
import org.openmrs.module.datalogging.filter.FilterUtils;

/**
 *
 */
public class LogicEventHandler extends OpenmrsEventHandler {
	
	/**
	 * @see org.openmrs.module.datalogging.handler.event.OpenmrsEventHandler#registerFilters()
	 */
	@Override
	protected void registerFilters() {
		registerFilter("logic");
	}
	
	/**
     * @see org.openmrs.module.datalogging.handler.event.OpenmrsEventHandler#supportFilter(java.lang.String)
     */
    @Override
    public boolean supportFilter(String filterName) {
    	// TODO: logic doesn't have handler, so we override this method
    	return getSupportedFilters().contains(filterName);
    }

	/**
	 * @see org.openmrs.module.datalogging.handler.event.EventHandler#allow(org.openmrs.module.datalogging.configuration.Event,
	 *      java.lang.Object)
	 */
	@Override
	public boolean allow(Event event, Object object) {
		String eventFilters[] = StringUtils.split(event.getEventFilter(), FilterUtils.EXPRESSION_SEPARATOR);
		boolean allow = false;
		for (String eventFilter : eventFilters) {
			String filterKey = eventFilter.substring(0, eventFilter.indexOf(FilterUtils.KEY_SEPARATOR));
			if (supportFilter(filterKey)) {
				String filterValue = eventFilter.substring(eventFilter.indexOf(FilterUtils.KEY_SEPARATOR) + 1);
				String[] filterValues = StringUtils.split(filterValue, FilterUtils.VALUE_SEPARATOR);
				for (String value : filterValues)
					if (StringUtils.equals(value, String.valueOf(object)))
						allow = true;
			}
		}
		return allow;
	}
	
}
